const mongoose = require('mongoose');
const deviceSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    trim: true
  },
  type: {
    type: String,
    required: true,
    enum: ['camera', 'sensor', 'access_control', 'alarm', 'lighting', 'hvac']
  },
  location: {
    type: String,
    required: true
  },
  status: {
    type: String,
    enum: ['online', 'offline', 'maintenance', 'error'],
    default: 'offline'
  },
  ip: {
    type: String,
    required: true,
    unique: true
  },
  port: {
    type: Number,
    default: 80
  },
  lastHeartbeat: {
    type: Date,
    default: Date.now
  },
  specifications: {
    model: String,
    manufacturer: String,
    firmware: String,
    installDate: Date
  },
  metrics: {
    uptime: { type: Number, default: 0 },
    errorCount: { type: Number, default: 0 },
    lastError: String
  },
  createdBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  }
}, {
  timestamps: true
});

// 添加虚拟字段以匹配前端期望的字段名
deviceSchema.virtual('ipAddress').get(function() {
  return this.ip;
});

deviceSchema.virtual('model').get(function() {
  return this.specifications?.model || '';
});

deviceSchema.virtual('manufacturer').get(function() {
  return this.specifications?.manufacturer || '';
});

deviceSchema.virtual('installDate').get(function() {
  return this.specifications?.installDate ? this.specifications.installDate.toISOString().split('T')[0] : '';
});

// 确保虚拟字段在JSON序列化时包含
deviceSchema.set('toJSON', { virtuals: true });
deviceSchema.set('toObject', { virtuals: true });

module.exports = mongoose.model('Device', deviceSchema);
